package bangbang.upanddown;

import bangbang.config.AliyunOssProperties;
import com.aliyun.oss.OSSClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;

@Service
public class FileUpload {
    // 自动注入
    @Autowired
    private AliyunOssProperties aliyunOssProperties;

    public  boolean  FileUpload(File file, String BucketName){
        String endpoint=aliyunOssProperties.getEndpoint();
        String accessKeyId =aliyunOssProperties.getAccessKeyId();
        String accessKeySecret =aliyunOssProperties.getAccessKeySecret();
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        String  objectName = "";
        if(file!=null){
            try {
                objectName=file.getName();
                //判断是否有特殊字符”+“ 号 官方建议过滤这些带有特殊字符的文件，否则会出现签名不匹配的问题，具体请看问题总结
                if(objectName.contains("+")){
                    objectName=objectName.replaceAll("\\+","%2b");
                }
                //  String  objectNameTest ="";
                //  objectNameTest= URLEncoder.encode(objectName,"utf-8").replaceAll("%2B","%2b");
                //  objectNameTest= URLDecoder.decode(objectName,"utf-8");
                //   System.out.println(objectNameTest);
                // 上传文件。<yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
                ossClient.putObject(BucketName, objectName,file);//("D:\\TestFile\\OSS_Flie\\RocketMQ.txt"));
                // 关闭OSSClient。
                ossClient.shutdown();
            }catch (Exception e){
                e.printStackTrace();
                return  false;
            }

        }
        //调用方法查询文件是否存在
        return   FileExites(objectName,BucketName);
    }
    /**判断文件是否存在*/
    public  boolean FileExites(String objectName,String bucketName){
        String endpoint=aliyunOssProperties.getEndpoint();
        String accessKeyId =aliyunOssProperties.getAccessKeyId();
        String accessKeySecret =aliyunOssProperties.getAccessKeySecret();
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        // 判断文件是否存在。doesObjectExist还有一个参数isOnlyInOSS，如果为true则忽略302重定向或镜像；如果
        //为false，则考虑302重定向或镜像。
        boolean found = ossClient.doesObjectExist(bucketName, objectName);
        if(found){
            System.out.println("上传成功！");
        }else{
            System.out.println("上传失败！");
        }
        System.out.println(found);
        return  found;
    }

}
